<template>
    <div>
        <Category :scene="scene"></Category>
        <el-card style="margin: 10px 0;">
            <div v-show="scene == 0">
                <el-button @click="addAttr" type="primary" icon="Plus" :disabled="!categoryStore.c3Id">添加属性</el-button>
                <el-table :border="true" style="margin: 10px 0;" :data="attrArr">
                    <el-table-column label="序号" type="index" align="center" width="80px" />
                    <el-table-column label="属性名称" width="120px" prop="attrName" />
                    <el-table-column label="属性值名称">
                        <template #default="scope">
                            <span v-for="attrValue in scope.row.attrValueList" :key="attrValue.id">
                                <el-tag :style="{ margin: '5px' }">{{ attrValue.valueName }}</el-tag>
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120px">
                        <template #default="scope">
                            <el-button @click="updateAttr(scope.row)" type="primary" size="small" icon="Edit"
                                title="修改"></el-button>
                            
                            <el-popconfirm :title="`确定要删除${scope.row.attrName}吗？`" width="200px" @confirm="deleteAttr(scope.row.id)">
                                <template #reference>
                                    <el-button type="danger" size="small" icon="Delete"></el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-show="scene == 1">
                <!--展示添加属性与修改数据的jiegou-->
                <el-form :inline="true">
                    <el-form-item label="属性名称">
                        <el-input placeholder="请输入属性名称" v-model="attrParams.attrName"></el-input>
                    </el-form-item>
                </el-form>
                <el-button @click="addAttrValue" :disabled="!attrParams.attrName" type="primary"
                    icon="Plus">添加属性值</el-button>
                <el-button @click="cancel">取消</el-button>
                <el-table :border="true" style="margin: 10px 0;" :data="attrParams.attrValueList">
                    <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                    <el-table-column label="属性值名称">
                        <template #default="scope">
                            <el-input :ref="(vc: any) => inputArr[scope.$index] = vc" v-if="scope.row.flag"
                                @blur="toLook(scope.row)" placeholder="请输入属性值名称"
                                v-model="scope.row.valueName"></el-input>
                            <div v-else @click="toEdit(scope.$index, scope.row)" style="width: 200px">{{
                                scope.row.valueName }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="属性值操作">
                        <template #default="scope">
                            <el-button type="primary" size="small" icon="Delete"
                                @click="deleteAttrValue(scope.$index)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" @click="save" :disabled="attrParams.attrValueList.length < 1">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import useCategoryStore from '@/store/modules/category';
import { reqAddOrUpdateAttr, reqAttr, reqRemoveAttr } from '@/api/product/attr';
import { nextTick, onBeforeUnmount, reactive, ref, watch } from 'vue';
import type { Attr, AttrResponseData, AttrValue } from '@/api/product/attr/type';
import { ElMessage } from 'element-plus';

let categoryStore = useCategoryStore()
//存储已有的属性与属性值
let attrArr = ref<Attr[]>([])
//定义card组件内容切换变量
let scene = ref(0)

//收集新增的属性数据
let attrParams = reactive<Attr>({
    attrName: '',
    attrValueList: [],
    categoryId: '',
    categoryLevel: 3
})
let inputArr = ref<any>([])
//监听仓库三级分类ID（categoryStore.c3Id）变化
watch(() => categoryStore.c3Id, async () => {
    //清空已有的属性与属性值
    attrArr.value = []
    //保证三级分类选中时才能发请求
    if (!categoryStore.c3Id) return
    //重新获取已有的属性与属性值
    getAttr()
});
//获取已有的属性与属性值方法
const getAttr = async () => {
    try {
        //获取分类ID
        const { c1Id, c2Id, c3Id } = categoryStore;
        const result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id);
        if (result.code === 200) {
            attrArr.value = result.data
        }
    } catch (error) {
        console.error('Error:', error);
    }
}
const addAttr = () => {
    //先清空数据再赋值
    Object.assign(attrParams, {
        attrName: '',
        attrValueList: [],
        categoryId: categoryStore.c3Id,
        categoryLevel: 3
    })
    //切换到添加属性的界面
    scene.value = 1
}

const updateAttr = (row: Attr) => {
    scene.value = 1
    // Object.assign(attrParams, row)  //将row数据赋值给attrParams，这是浅拷贝
    Object.assign(attrParams, JSON.parse(JSON.stringify(row)))  //将row数据赋值给attrParams，这是深拷贝
}

const cancel = () => {
    scene.value = 0
}
//添加属性值按钮的问题
const addAttrValue = () => {
    attrParams.attrValueList.push({ attrId: attrParams.id, valueName: '', flag: true })
    nextTick(() => {
        inputArr.value[attrParams.attrValueList.length - 1].focus()
    })
}

const save = () => {
    reqAddOrUpdateAttr(attrParams).then((result) => {
        if (result.code === 200) {
            ElMessage.success('保存成功')
            cancel()
            //重新获取已有的属性与属性值
            getAttr()
        } else {
            ElMessage.error(result.message)
        }
    })
}

const toLook = (row: AttrValue) => {
    //非法情况判断
    if (row.valueName.trim() === '') return
    let repeat = attrParams.attrValueList.find(item => {
        if (item !== row) {
            return item.valueName === row.valueName
        }
        return false
    })
    if (repeat) {
        ElMessage.warning('属性值不能重复')
        //去掉当前row
        attrParams.attrValueList.splice(attrParams.attrValueList.indexOf(row), 1)
        return
    }
    row.flag = false
}

const toEdit = async (index: number, row: AttrValue) => {
    row.flag = true

    //获取焦点
    await nextTick();
    console.log(inputArr.value[index])
    inputArr.value[index].focus()
}

const deleteAttrValue = (index: number) => {
    attrParams.attrValueList.splice(index, 1)
}

const deleteAttr = (attrId: number) => {
    reqRemoveAttr(attrId).then((result) => {
        if (result.code === 200) {
            ElMessage.success('删除成功')
            //重新获取已有的属性与属性值
            getAttr()
        } else {
            ElMessage.error(result.message)
        }
    })
}

//路由组件销毁的时候，把仓库分类相关数据清空
onBeforeUnmount(() => {
    categoryStore.$reset()
})
</script>

<style scoped></style>